package spring.cloud.tasks.executor.listener.failover;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import spring.cloud.tasks.executor.utils.log.LogUtils;

@Slf4j
@Setter
@Getter
class RunningPathListener implements NodeCacheListener {

    private final FailoverListenerHolder failoverListener;
    private int item;

    public RunningPathListener(FailoverListenerHolder failoverListener, int item) {
        this.failoverListener = failoverListener;
        this.item = item;
    }

    @Override
    public void nodeChanged() throws Exception {
        failoverListener.nodeCacheOrTreeCacheManager.getExecutorService().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    if (failoverListener.isShutdown) {
                        return;
                    }
                    if (!failoverListener.executeService.isRunning(item)) {
                        failoverListener.failover(item);
                    }
                } catch (Throwable t) {
                    LogUtils.error(log, failoverListener.taskId, t.getMessage(), t);
                }
            }
        });
    }
}
